<?php

include dirname(__FILE__) . '/../../class/_core.php';
include dirname(__FILE__) . '/../../class/department.php';

$id = Util::get('id');

$Db = Db::get_instance();

$productInfo = $Db->query("SELECT
	`fo`.*,`fm`.product_model,`fm`.gongyi
FROM
	`fac_product_order` `fo`
LEFT JOIN `fac_product_mess` `fm` on `fm`.product_id = `fo`.product_id
WHERE
	`product_order_id` = $id;");

$department = new department();
$view = $department->department_view_all();

$code = $productInfo[0]['product_order_code'];

if ($code != "") {
    $twhere .= " AND po.product_order_id = '$id' ";
}

$arr_rate = 0.00;
$arr_rate_count = 0;

foreach ($view as &$v) {
    $text = "
        SELECT
	po.product_order_code,pm.product_model,pm.product_code,pm.gongyi, (
		SELECT
			SUM(number)
		FROM
			fac_department_receive_record frr
		WHERE
			frr.department_id = fdr.department_id
		AND frr.order_id = fdr.order_id
	) as getX,
	SUM(fdr.number) as numberX
FROM
	fac_department_product_record fdr
LEFT JOIN fac_product_order po on po.product_order_id = fdr.order_id
LEFT JOIN fac_product_mess pm on pm.product_id = fdr.product_id
WHERE
	fdr.department_id = $v[department_id] $twhere
GROUP BY fdr.order_id,fdr.product_id
            ORDER BY
	numberX DESC";
    $v['produce'] = Db::get_instance()->query($text);
    foreach ($v['produce'] AS &$p) {
        if ($p['getX'] == 0 || $p['numberX'] == 0) {
            $p['rate'] = false;
        } else {
            $p['rate'] = round(($p['numberX'] / $p['getX']) * 100, 2);
            $arr_rate += $p['rate'];
            $arr_rate_count++;
        }
    }
}

$arr_rate = $arr_rate / $arr_rate_count;

// 获取生产编号
$pCode = Db::get_instance()->query("SELECT product_order_id,product_order_code FROM fac_product_order");

$Smarty->assign('cd', $code);
$Smarty->assign('pCode', $pCode);
$Smarty->assign('from', $from);
$Smarty->assign('to', $to);
$Smarty->assign('dept', $view);
$Smarty->assign('pinfo', $productInfo[0]);
$Smarty->assign('avg_rate', $arr_rate);
$Smarty->assign('finishOrderList', $productInfo[0]['order_state'] == '已完成' ? true : false);
$Smarty->display('produce/produce_infos.tpl');